package com.kongzue.baseokhttpv3.newslice;


import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.JsonResponseListener;
import com.kongzue.baseokhttp.listener.ParameterInterceptListener;
import com.kongzue.baseokhttp.listener.ResponseInterceptListener;
import com.kongzue.baseokhttp.listener.UploadProgressListener;
import com.kongzue.baseokhttp.util.*;
import com.kongzue.baseokhttpv3.ResourceTable;
import com.kongzue.baseokhttpv3.util.JsonUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import org.apache.http.util.TextUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class PostAbilitySlice extends AbilitySlice {
    private TextField biaodanFiledUrl;
    private TextField biaodanInput;
    private TextField jsonFiledUrl;
    private TextField jsonInput;
    private Text content;
    private Button biaodan, json, file;
    private TextField postFiledUrl;
    private TextField FileInput;
    private String path;
    private TextField url;
    private Button click;
    private TextField cookie;

    private void header() {

        BaseOkHttpConfig.getInstance().setParameterInterceptListener(new ParameterInterceptListener<JsonMap>() {
            @Override
            public JsonMap onIntercept(Context context, String url, JsonMap o) {
                return null;
            }
        });
        BaseOkHttpConfig.getInstance().setResponseInterceptListener(new ResponseInterceptListener() {
            @Override
            public boolean onResponse(Context context, String url, String response,
                                      Exception error) {
                if (error != null) {
                    return true;
                } else {
                    // Log.i("!!!", "onResponse: " + response);
                    return true;
                }
            }
        });
        JsonMapConfig.getInstance().setPreParsing(true);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_post_new);
        biaodanFiledUrl = (TextField) findComponentById(ResourceTable.Id_post_biaodan_url);
        biaodanInput = (TextField) findComponentById(ResourceTable.Id_post_biaodan_input);
        jsonFiledUrl = (TextField) findComponentById(ResourceTable.Id_post_json_url);
        jsonInput = (TextField) findComponentById(ResourceTable.Id_post_json_input);
        content = (Text) findComponentById(ResourceTable.Id_back_content);
        biaodan = (Button) findComponentById(ResourceTable.Id_post_biaodan_button);
        json = (Button) findComponentById(ResourceTable.Id_post_json_button);
        file = (Button) findComponentById(ResourceTable.Id_post_file_button);
        cookie = (TextField) findComponentById(ResourceTable.Id_cookie_input);
        cookie.setText("{\n" +
                "    \"test\": \"177c070d1922f938ccee95b6bd04df0b\"}");
        postFiledUrl = (TextField) findComponentById(ResourceTable.Id_post_file_url);
        FileInput = (TextField) findComponentById(ResourceTable.Id_post_file_name);
        postFiledUrl.setText("http://hn216.api.yesapi.cn/?");
        FileInput.setText("word_test.docx");
        path = getExternalCacheDir().getParent() + "/";
        url = (TextField) findComponentById(ResourceTable.Id_get_url);
        click = (Button) findComponentById(ResourceTable.Id_get_button);
        url.setText("/mock/5009ac87331ccbc9fce98559554f58a5/test/get_api");
        biaodanFiledUrl.setText("/mock/5009ac87331ccbc9fce98559554f58a5/test/test_postform");
        biaodanInput.setText("{\n" +
                "    \"areaId\": \"58238\",\n" +
                "    \"areaType\": \"2\",\n" +
                "    \"lifestyleType\": \"1\",\n" +
                "    \"lifestyleDate\": \"03月28日\"\n" +
                "}");
        jsonFiledUrl.setText("/mock/5009ac87331ccbc9fce98559554f58a5/test/test_postjson");
        jsonInput.setText("{\n" +
                "    \"key\": \"177c070d1922f938ccee95b6bd04df0b\",\n" +
                "    \"city\": \"上海市\"\n" +
                "}");

        header();
        onclick();
    }

    private void onclick() {
        file.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (!TextUtils.isEmpty(postFiledUrl.getText().toString()) && !TextUtils.isEmpty(FileInput.getText().toString())) {
                    String filename = FileInput.getText().toString();
//                    image/gif ：gif图片格式    
//                image/jpeg ：jpg图片格式 
//                image/png：png图片格式
                    String url = "";
                    if (filename.contains(".png") || filename.contains(".gif") || filename.contains(".jpg") || filename.contains(".jpeg") || filename.contains(".webp")) {
                        url = "s=App.CDN.UploadImg";
                    } else {
                        url = "s=App.CDN.UploadOffice";

                    }

                    uploadFile(url);

                } else {
                    ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                    toastDialog.setText("err, is null").setDuration(1000).show();
                }

            }
        });
        biaodan.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    if (!TextUtils.isEmpty(biaodanInput.getText().toString())) {
                        String json = biaodanInput.getText().toString();
                        Map<String, Object> jsonObject = null;
                        try {
                            jsonObject = JsonUtil.jsonToMap(json);
                            Map<String, String> params = new HashMap<>();

                            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                                params.put(entry.getKey(), entry.getValue().toString());
                            }
                            postEnqueue(biaodanFiledUrl.getText().toString(), params);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        postEnqueue(biaodanFiledUrl.getText().toString(), null);

                    }
                } catch (Exception e) {
                    ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                    toastDialog.setText("Invalid forma").setDuration(1000).show();
                }
            }
        });
        json.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    if (!TextUtils.isEmpty(jsonInput.getText().toString())) {
                        String json = jsonInput.getText().toString();

                        postJson(jsonFiledUrl.getText().toString(), json);

                    } else {
                        postJson(jsonFiledUrl.getText().toString(), null);

                    }
                } catch (Exception e) {
                    ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                    toastDialog.setText("Invalid forma").setDuration(1000).show();
                }
            }
        });
        click.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (!TextUtils.isEmpty(url.getText().toString())) {
                    getbiaodan(url.getText().toString(), null);
                } else {
                    ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                    toastDialog.setText("url is not null").setDuration(1000).show();
                }
            }
        });
    }

    private void getbiaodan(final String url, Map<String, String> params) {
        BaseOkHttpConfig.getInstance().setSSLInAssetsFileName(null);
        Parameter parameter = new Parameter();
        if (null != params) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameter.add(entry.getKey(), entry.getValue());
            }
        }
        HttpRequest.GET(PostAbilitySlice.this, url,
                parameter, new JsonResponseListener() {
                    @Override
                    public void onResponse(JsonMap main, Exception error) {
                        if (error == null) {
                            PostAbilitySlice.this.getContext().getMainTaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                                    toastDialog.setText("OK").setDuration(1000).show();
                                    content.setText(main.toString());


                                }
                            });
                            //
                        } else {
                            ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                            toastDialog.setText("time out").setDuration(1000).show();
                        }
                    }
                });

    }


    private void postjson(final String url, String params) {
        BaseOkHttpConfig.getInstance().setSSLInAssetsFileName(null);

        HttpRequest.JSONPOST(PostAbilitySlice.this, jsonFiledUrl.getText().toString(),
                params, new JsonResponseListener() {
                    @Override
                    public void onResponse(JsonMap main, Exception error) {
                        if (error == null) {
                            PostAbilitySlice.this.getContext().getMainTaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                                    toastDialog.setText("OK").setDuration(1000).show();
                                    content.setText(main.toString());


                                }
                            });
                            //
                        } else {
                            ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                            toastDialog.setText("time out").setDuration(1000).show();
                        }
                    }
                });

    }

    public void postJson(final String url, String params) {
        postjson(url, params);
    }

    private void updatenew(String url) {
        String paths = path + FileInput.getText().toString();
        File file = new File(paths);
        if (!file.exists()) {
            ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
            toastDialog.setText("File path does not exist").setDuration(1000).show();
            return;
        }
        try {

            List<File> fileList = new ArrayList<File>();
            fileList.add(file);
            HttpRequest.build(PostAbilitySlice.this,
                    "https://hn216.api.yesapi.cn/?" + url).addHeaders("Charset",
                    "UTF-8").addParameter("return_data", "0").addParameter("app_key",
                    "DC43EBA4682FE70A316898472E5A0D2F").addParameter("sign",
                    "7BDB268AEED6EF49B0B027B8CCDE5EC8").addParameter("file",
                    fileList).setUploadProgressListener(
                    new UploadProgressListener() {
                        @Override
                        public void onUpload(float percentage,
                                             long current, long total,
                                             boolean done) {
                            if (done) {
                                ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                                toastDialog.setText("OK").setDuration(1000).show();
                            }

                            PostAbilitySlice.this.getContext().getMainTaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {

                                    try {
                                        content.setText("上传进度----》" + (int) (current / (total * 1.0f) * 100));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }


                                }
                            });
                        }
                    }).doPost();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadFile(String url) {
        updatenew(url);
    }

    private void postbiaodan(final String url, Map<String, String> params) {
        BaseOkHttpConfig.getInstance().setSSLInAssetsFileName(null);
        Parameter parameter = new Parameter();
        if (null != params) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameter.add(entry.getKey(), entry.getValue());
            }
        }

        HttpRequest.POST(PostAbilitySlice.this, biaodanFiledUrl.getText().toString(),
                parameter, new JsonResponseListener() {
                    @Override
                    public void onResponse(JsonMap main, Exception error) {
                        if (error == null) {
                            PostAbilitySlice.this.getContext().getMainTaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                                    toastDialog.setText("OK").setDuration(1000).show();
                                    content.setText(main.toString());


                                }
                            });
                            //
                        } else {
                            content.setText(error.getMessage());
                            ToastDialog toastDialog = new ToastDialog(PostAbilitySlice.this);
                            toastDialog.setText("time out").setDuration(1000).show();
                        }
                    }
                });

    }


    public void postEnqueue(final String url, Map<String, String> params) {
        postbiaodan(url, params);
    }
}
